package heman.server.entities;

import java.util.ArrayList;

/**
 * All functions of tables. Some of them are synchronized.
 * 
 * @author Wenlong Liu
 *
 */

public class TableManager {
	/** Number of tables*/
	public static final int maxTables=100;
	
	ArrayList<Table> tableList=new ArrayList<Table>();
	
	static TableManager tm=null;
	private TableManager(){
		//Init Tables
		for (int i = 1; i <=maxTables; i++) {
			addTable(new Table(Integer.toString(i)));
		}
	}
	
	public static TableManager getInstance(){
		if (tm==null)
			synchronized (TableManager.class) {
				if (tm==null)
					return tm=new TableManager();
				else return tm;
			}
			
		return tm;
	}
	
	
	private  boolean  addTable(Table t){
		if (tableList.size()<maxTables){
			
			synchronized (tableList){
				tableList.add(t);
			}
			return true;
		}else return false;
			
		
	}
	public boolean removeTable(Table table){
		boolean b=false;
		synchronized (tableList){
			b=tableList.remove(table);
		}
		return b;
	}

	public Table getTable(String id){
		Table table=null;
		synchronized (tableList) {
			for (Table t:tableList){
				if (t.getID().equals(id)){
					table=t;
					break;
				}
			}
		}
		
		return table;
	}
	public String onTable(Player p){
		synchronized (tableList) {
			for (Table t:tableList){
				if (t.onTable(p)){
					return t.getID(); 
					//break;
				}
			}
			return null;
		}
	}
	public String onTable(String pID){
		synchronized (tableList) {
			for (Table t:tableList){
				if (t.onTable(pID)){
					return t.getID(); 
					//break;
				}
			}
			return null;
		}
	}
	public String toXML(){
		StringBuilder sb=new StringBuilder();
		
		synchronized (tableList){
			for (Table t:tableList)
				sb.append(t.toXML()	);
			
		}
		
		return sb.toString();
	}
	
}
